package com.hnly.djdl.components

import android.graphics.Bitmap
import android.net.http.SslError
import android.util.Log
import android.webkit.ConsoleMessage
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIos
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.hnly.djdl.theme.MainThemeColor
import com.hnly.djdl.BuildConfig


@Composable
fun TitleCommonDialog(
    title: String = "标题",
    height: Dp = 600.dp,
    onDismissRequest: () -> Unit,
    onSave: () -> Unit = {},
    rightContent: @Composable RowScope.() -> Unit = {
        TextButton(onClick = onSave) {
            Text(text = "保存")
        }
    },
    content: @Composable ColumnScope.() -> Unit,
) {
    CommonDialog(onDismissRequest = onDismissRequest) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .height(height)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Icon(imageVector = Icons.Filled.ArrowBackIos,
                    contentDescription = null,
                    modifier = Modifier.clickable { onDismissRequest() })
                Text(text = title, style = TextStyle.Default.copy(fontSize = 26.sp))
                rightContent()
            }
            content()
        }
    }
}

@Composable
fun CenterTextDialog(
    title: String = "标题",
    height: Dp = 600.dp,
    properties: DialogProperties = DialogProperties(),
    onDismissRequest: () -> Unit,
    content: @Composable ColumnScope.() -> Unit,
) {
    CustomDialog(
        onDismissRequest = onDismissRequest,
        height = height,
        properties = properties,
        leftTitleContent = { Text("") },
        centerTitleContent = {
            Text(text = title, style = TextStyle.Default.copy(fontSize = 26.sp))
        },
        rightTitleContent = { Text("") },
        content = content
    )
}

@Composable
fun CustomDialog(
    onDismissRequest: () -> Unit,
    height: Dp = 600.dp,
    properties: DialogProperties = DialogProperties(),
    leftTitleContent: @Composable RowScope.() -> Unit = {
        Icon(
            imageVector = Icons.Filled.ArrowBackIos,
            contentDescription = null,
            modifier = Modifier.clickable { onDismissRequest() })
    },
    centerTitleContent: @Composable RowScope.() -> Unit = {
        Text(
            text = "标题",
            style = TextStyle.Default.copy(fontSize = 26.sp)
        )
    },
    rightTitleContent: @Composable RowScope.() -> Unit = { TextButton(onClick = {}) { Text(text = "保存") } },
    content: @Composable ColumnScope.() -> Unit,
) {
    CommonDialog(onDismissRequest = onDismissRequest, properties = properties) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .height(height)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                leftTitleContent()
                centerTitleContent()
                rightTitleContent()
            }
            content()
        }
    }
}

@Composable
fun CommonDialog(
    onDismissRequest: () -> Unit,
    properties: DialogProperties = DialogProperties(
        dismissOnBackPress = true,
        dismissOnClickOutside = true
    ),
    content: @Composable () -> Unit,
) {
    Dialog(
        onDismissRequest = { onDismissRequest() },
        properties = properties
    ) {
        Surface(
            shape = MaterialTheme.shapes.medium,
            elevation = 8.dp,
            color = Color.White,
            content = content
        )
    }
}


@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun WebViewDialog(
    url: String, modifier: Modifier = Modifier,
    properties: DialogProperties = DialogProperties(
        dismissOnBackPress = true,
        dismissOnClickOutside = true,
        usePlatformDefaultWidth = false
    ),
    onDismissRequest: () -> Unit) {
    CommonDialog(onDismissRequest = onDismissRequest, properties = properties) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        ) {
            val context = LocalContext.current
            var showLoading = remember { mutableStateOf(true) }
            AndroidView(modifier = modifier.fillMaxHeight(), factory = {
                WebView(context).apply {
                    webChromeClient = object : WebChromeClient() {
                        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                            if (BuildConfig.DEBUG) {
                                Log.i("WebChromeClient", "${consoleMessage?.message()}")
                            }
                            return super.onConsoleMessage(consoleMessage)
                        }
                    }
                    webViewClient = object : WebViewClient() {
                        override fun onReceivedSslError(
                            view: WebView?,
                            handler: SslErrorHandler?,
                            error: SslError?,
                        ) {
                            super.onReceivedSslError(view, handler, error)
                            if (BuildConfig.DEBUG) {
                                Log.i("WebViewClient", "onReceivedSslError")
                            }
                        }

                        override fun shouldOverrideUrlLoading(
                            view: WebView?,
                            request: WebResourceRequest?,
                        ): Boolean {
                            return super.shouldOverrideUrlLoading(view, request)
                        }

                        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                            super.onPageStarted(view, url, favicon)
                            showLoading.value = true
                        }

                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            showLoading.value = false
                        }
                    }

                    settings.javaScriptEnabled = true // Enable JavaScript if needed
                    settings.domStorageEnabled = true
                    settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
                    settings.loadWithOverviewMode = true
                    loadUrl(url)
                }
            },
                update = {}
            )
            if (showLoading.value) {
                val infiniteTransition = rememberInfiniteTransition()
                val progressAnimationValue by infiniteTransition.animateFloat(
                    initialValue = 0.0f,
                    targetValue = 1.0f,
                    animationSpec = infiniteRepeatable(animation = tween(900))
                )
                CircularProgressIndicator(
                    progress = progressAnimationValue,
                    modifier = Modifier.size(80.dp).align(Alignment.Center),
                    color = MainThemeColor,
                    strokeWidth = 8.dp
                )
            }
        }
    }
}